package cn.web03.controller;

import cn.web03.websocket.po.SocketMessage;
import cn.web03.websocket.po.SocketMessageT;
import cn.web03.websocket.po.SocketUser;
import cn.web03.websocket.service.SocketMessageService;
import cn.web03.websocket.service.SocketUserService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.*;
/**
 * @author 零三 2020.06
 * https://web03.cn
 */
@Controller
public class ChatRoom {

    @Autowired
    private SocketUserService socketUserService;
    @Autowired
    private SocketMessageService socketMessageService;

    @GetMapping("/chatRoom")
    public String chatRoom() {
        return "chat_room";
    }

    @PostMapping("/chatRoom/login")
    @ResponseBody
    public SocketUser socketLogin(@RequestBody SocketUser socketUser) {
        SocketUser result = socketUserService.checkedSocketUser(socketUser);
        if (result == null) {
            return null;
        }
        result.setPassword(null);
        return result;
    }

    @PostMapping("/chatRoom/register")
    @ResponseBody
    public int socketRegister(@RequestBody SocketUser socketUser) {
        socketUser.setLoginTime(new Date());
        List<SocketUser> socketUsers = socketUserService.getSocketUsers();
        for (SocketUser s : socketUsers) {
            if (s.getNickname().equals(socketUser.getNickname())) {
                return 2;//昵称已存在
            }
            if (s.getUsername().equals(socketUser.getUsername())) {
                return 3;//账号已存在
            }
        }
        SocketUser result = socketUserService.saveSocketUsers(socketUser);
        if (result == null) return -1;//注册失败
        return 1;
    }

    @PostMapping("/chatRoom/user/info")
    @ResponseBody
    public Object getUserInfo(@RequestBody Long socketUserId) {
        SocketUser result = socketUserService.getSocketUser(socketUserId);
        if (result == null) {
            return null;
        }
        result.setPassword(null);
        return JSON.parseObject(JSON.toJSONString(result));
    }

    @PostMapping("/chatRoom/group/message")
    @ResponseBody
    public List<SocketMessage> getSocketMessageTByDate(@RequestBody JSONObject jsonObject) {
         System.out.println(jsonObject);
        Date date = jsonObject.getDate("date");
        String launchId = jsonObject.getString("launchId");
        String receiveId = jsonObject.getString("receiveId");
        System.out.println(date);
        List<SocketMessageT> list;
        if (launchId!=null&&receiveId!=null){
            list = socketMessageService.getSocketMessageTByUser(launchId,receiveId,date);
        }else {
            list = socketMessageService.getSocketMessageTByDate(date);
        }
        List<SocketMessage> newList = new ArrayList<>();

        for (SocketMessageT socketMessageT : list) {
            SocketMessage socketMessage = new SocketMessage(socketMessageT.getId(), socketMessageT.getLaunchId(), strToBean(socketMessageT.getLaunchUser(), SocketUser.class), socketMessageT.getReceiveId(), strToBean(socketMessageT.getReceiveUser(), SocketUser.class), socketMessageT.getContent(), socketMessageT.getType(), socketMessageT.getCreateTime());
            System.out.println(socketMessage);
            newList.add(socketMessage);
//            if (socketMessageT.getLaunchUser() != null && !"null".equals(socketMessageT.getLaunchUser()) && "".equals(socketMessageT.getLaunchUser())){
//
//            }
        }
        return newList;
    }

    /**
     * 获取相关联系人
     */
    @GetMapping("/chatRoom/users/relevant/{userId}")
    @ResponseBody
    public List<SocketUser> getSocketUserRelevant(@PathVariable String userId) {
        List<String> socketUserRelevant = socketMessageService.getSocketUserRelevant(userId);
        //去重
        Map map = new HashMap();
        for(String socketUserStr : socketUserRelevant){
            SocketUser socketUser = strToBean(socketUserStr, SocketUser.class);
            map.put(socketUser.getId(),socketUser);
        }
        List<SocketUser> result = new ArrayList(map.values());
        return result;
    }

    /**
     * 将字符串转化为指定的Java类型对象
     */
    public static <T> T strToBean(String str, Class<T> clazz) {    //将字符串转变为指定类型的Java对象
        if (str == null || clazz == null || str.length() == 0) {
            return null;
        }
        if (clazz == int.class || clazz == Integer.class) {
            return (T) Integer.valueOf(str);
        } else if (clazz == long.class || clazz == Long.class) {
            return (T) Long.valueOf(str);
        } else if (clazz == float.class || clazz == Float.class) {
            return (T) Float.valueOf(str);
        } else if (clazz == String.class) {
            return (T) str;
        } else return (T) JSON.toJavaObject(JSON.parseObject(str), clazz);
        //JSON.parseObject(str)：将字符串转化为一个对象
        //JSON.toJavaObject(JSON，class<T>)：将一个JSON对象转化为一个clazz类型的Java对象。
    }
    /**
     * 将时间戳转换为时间
     */
    public static String stampToDate(String s){
        String res;
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        long lt = new Long(s);
        Date date = new Date(lt);
        res = simpleDateFormat.format(date);
        return res;
    }
}
